package com.hsq.spzx.product.utils;


import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.hsq.spzx.model.entity.product.Category;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hsq
 * @date 2025-06-04 下午6:16
 */
public class MenuHelper {

    /**
     * 使用递归方法建菜单
     * @param CategoryList
     * @return
     */
    public static List<Category> buildTree(List<Category> CategoryList){
        List<Category> trees = new ArrayList<>();
        for (Category Category: CategoryList) {
            if (Category.getParentId() == 0L) {
                trees.add(findChildren(Category, CategoryList));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param Category
     * @param categoryList
     * @return
     */
    private static Category findChildren(Category Category,
                                         List<Category> categoryList) {
        Category.setChildren(new ArrayList<>());
        for (Category s: categoryList) {
            if (s.getParentId().longValue() == Category.getId().longValue()) {
                Category.getChildren().add(findChildren(s, categoryList));
            }
        }
        return Category;
    }

    public static List<Category> buildTree1(List<Category> allCategoryList) {
        List<Category> oneCategoryList = allCategoryList.stream()
        .filter(category -> category.getParentId() == 0)
        .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(oneCategoryList)) {
            oneCategoryList.forEach(category -> {
                category.setChildren(findChildren1(category, allCategoryList));
            });
        }
        return oneCategoryList;
    }

    private static List<Category> findChildren1(Category category,
                                         List<Category> allCategoryList) {
        List<Category> categoryList = new ArrayList<>();
        allCategoryList.forEach(item -> {
            if (item.getParentId().longValue() == category.getId().longValue()) {
                item.setChildren(findChildren1(item, allCategoryList));
                categoryList.add(item);
            }
        });
        return categoryList;
    }
}
